package dr.JokeTalkerServer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.util.List;
import java.util.concurrent.Semaphore;

import dr.joketalker.dao.FactoryDAO;
import dr.joketalker.dao.JokeDAO;
import dr.joketalker.dao.json.JSONJoke;
import dr.joketalker.entity.Joke;
import dr.joketalker.model.MyFtpClient;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
import org.json.JSONException;

public class Start {


	protected JokeDAO jokeDao = FactoryDAO.getJokeDao();
	protected MyFtpClient myFtpClient = MyFtpClient.getInstance();;
	protected YouTubeClient ytClient = new YouTubeClient();
	
	
	protected File logFile;
	
	 Semaphore s1 = new Semaphore(0);

	
	public Start(){

		System.out.println("Main");
		
		
		
		List<Joke> listJoke = jokeDao.readAllWhere(JSONJoke.LINKYT,"1",0);		

		
		int i = 0;
		for(Joke joke : listJoke){
			System.out.println(joke);
			
			deleteGeneratedFiles();
			
			downloadJoke(joke);		
			convert(joke);
		
			
			try {
				System.out.println("wait for convert");
				s1.acquire();
				System.out.println("convert end");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			

			ytClient.uploadJoke(joke);
			
			i++;
		}

		
		
    	
    	System.out.println(i+" jokes uploaded end");
	}
	
	
	public void deleteGeneratedFiles(){
		File file = new File("files/new.avi");
		
		if(file.exists()){
			file.delete();
		}
		
		file = new File("files/new.3gp");
		if(file.exists()){
			file.delete();
		}
	}
	
	
	public void downloadJoke(Joke joke){

		try {
			myFtpClient.connect();
			myFtpClient.login();			
	
			
			String fileName = "files/new.3gp";
			

    		FileOutputStream fos = new FileOutputStream(fileName);
    		
    		myFtpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
    		myFtpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
    		


		
			boolean res = myFtpClient.retrieveFile(joke.getLinkFtp(), fos);
			
			System.out.println("Download success " + res);
			fos.close();
			myFtpClient.logout();
			myFtpClient.disconnect();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
	}
	
	public String convert(Joke joke){
		String sourcePath = "files/new.3gp";
		
		String destinationPath = sourcePath.substring(0, sourcePath.length()-4) + ".avi";
		String ffmpegPath = "ffmpeg";
		String picturePath = "files/image.png";
		String command = ffmpegPath+ " -loop 1 -shortest -vframes 10 -i "; 
		
		command += picturePath;
		command += " " + "-i files/new.3gp";//+sourcePath;
		command += " " + destinationPath;
		//ffmpeg -loop 1 -shortest -i p.png -i a.3gp output.avi
		
		
		try {
				
			
			System.out.println("convert + |" + command);
		
			
			final Process p = Runtime.getRuntime().exec(command);
			
			 
			
			System.out.println("convert2");
            final BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));  
           
            
            new Thread(){
            	public void run() {
 
                    System.out.println("convert3");
        			 String line = null;  
        			try {
						while ((line = in.readLine()) != null) {  
						    System.out.println(line);  
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}  
        			System.out.println("endthread");
            	}
            }.start();
            	
            
            
			System.out.println("convert2");
            final BufferedReader in2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));  
            
            
            new Thread(){
            	public void run() {
 
                    System.out.println("convert3");
        			 String line = null;  
        			try {
						while ((line = in2.readLine()) != null) {  
						    System.out.println("error: "+line);  
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}  
        			System.out.println("endthread");
        			s1.release();
        			 p.exitValue();
            	}
            }.start();
            
 
			
			System.out.println("endwhile");
			/*
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));  
            System.out.println("convert3");
			 line = null;  
			while ((line = in.readLine()) != null) {  
			    System.out.println(line);  
			}  
			*/
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String result = destinationPath;
		return result;
	}
	

}
